package com.qf.kdxf.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.qf.kdxf.entity.facerecognition.ResponseData;
import com.qf.kdxf.util.common.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 明廷盛
 * @Date 2025/6/16 13:33
 * @Description
 */
public class FaceUtil {
    //人脸识别模块==》请求地址url的构建 构建url ==>共同使用
    public static String assembleRequestUrl(String requestUrl, String apiKey,
                                            String apiSecret) {
        URL url = null;
        // 替换调schema前缀 ，原因是URL库不支持解析包含ws,wss schema的url
        String httpRequestUrl = requestUrl.replace("ws://",
                "http://").replace("wss://", "https://");
        try {
            url = new URL(httpRequestUrl);
            //获取当前日期并格式化
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm: ss z ", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            String host = url.getHost();
            if (url.getPort() != 80 && url.getPort() != 443) {
                host = host + ":" + String.valueOf(url.getPort());
            }
            StringBuilder builder = new StringBuilder("host: ").append(host).append("\n").//
                    append("date: ").append(date).append("\n").//
                    append("POST ").append(url.getPath()).append(" HTTP/1.1");
            Charset charset = Charset.forName("UTF-8");
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset),
                    "hmacsha256");
            mac.init(spec);
            byte[] hexDigits =
                    mac.doFinal(builder.toString().getBytes(charset));
            String sha = Base64.getEncoder().encodeToString(hexDigits);
            String authorization = String.format("api_key=\"%s\", algorithm =\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
            String authBase =
                    Base64.getEncoder().encodeToString(authorization.getBytes(charset));
            return String.format("%s?authorization=%s&host=%s&date=%s",
                    requestUrl, URLEncoder.encode(authBase), URLEncoder.encode(host),
                    URLEncoder.encode(date));
        } catch (Exception e) {
            throw new RuntimeException("assemble requestUrl error:" + e.getMessage());
        }
    }

    //人脸识别模块 ==》获取响应结果
    public static ResponseData handleFaceContrastRes(String url, String
            bodyParam, Gson json) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-type", "application/json");
        String result = HttpUtil.doPost2(url, headers, bodyParam);
        if (result != null) {
            System.out.println("人脸识别接口调用结果：" + result);
            return json.fromJson(result, ResponseData.class);
        } else {
            return null;
        }
    }

    //人脸对比模块 参数获取
    public static String getXParam01(String imageBase641, String imageEncoding1,
                                     String imageBase642, String imageEncoding2, String appid, String serviceId) {
        JsonObject jso = new JsonObject();
        /** header **/
        JsonObject header = new JsonObject();
        header.addProperty("app_id", appid);
        header.addProperty("status", 3);
        jso.add("header", header);
        /** parameter **/
        JsonObject parameter = new JsonObject();
        JsonObject service = new JsonObject();
        service.addProperty("service_kind", "face_compare");
        JsonObject faceCompareResult = new JsonObject();
        faceCompareResult.addProperty("encoding", "utf8");
        faceCompareResult.addProperty("format", "json");
        faceCompareResult.addProperty("compress", "raw");
        service.add("face_compare_result", faceCompareResult);
        parameter.add(serviceId, service);
        jso.add("parameter", parameter);
        /** payload **/
        JsonObject payload = new JsonObject();
        JsonObject inputImage1 = new JsonObject();
        inputImage1.addProperty("encoding", imageEncoding1);
        inputImage1.addProperty("image", imageBase641);
        payload.add("input1", inputImage1);
        JsonObject inputImage2 = new JsonObject();
        inputImage2.addProperty("encoding", imageEncoding2);
        inputImage2.addProperty("image", imageBase642);
        payload.add("input2", inputImage2);
        System.out.println(jso.toString());
        jso.add("payload", payload);
        return jso.toString();
    }

    //人脸检测模块 参数获取
    public static String getXParam02(String imageBase641, String
            imageEncoding1, String appid, String serviceId) {
        JsonObject jso = new JsonObject();
        /** header **/
        JsonObject header = new JsonObject();
        header.addProperty("app_id", appid);
        header.addProperty("status", 3);
        jso.add("header", header);
        /** parameter **/
        JsonObject parameter = new JsonObject();
        JsonObject service = new JsonObject();
        service.addProperty("service_kind", "face_detect");
        //service.addProperty("detect_points", "1");//检测特征点
        //service.addProperty("detect_property", "1");//检测人脸属性
        JsonObject faceCompareResult = new JsonObject();
        faceCompareResult.addProperty("encoding", "utf8");
        faceCompareResult.addProperty("format", "json");
        faceCompareResult.addProperty("compress", "raw");
        service.add("face_detect_result", faceCompareResult);
        parameter.add(serviceId, service);
        jso.add("parameter", parameter);
        /** payload **/
        JsonObject payload = new JsonObject();
        JsonObject inputImage1 = new JsonObject();
        inputImage1.addProperty("encoding", imageEncoding1);
        inputImage1.addProperty("image", imageBase641);
        payload.add("input1", inputImage1);
        jso.add("payload", payload);
        System.out.println(jso.toString());
        return jso.toString();
    }
    //人脸特征检测===》组装http请求头

    /**
     * 组装http请求头
     */
    public static Map<String, String> buildHttpHeader(String imageName, String
            apikey, String appid) {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"image_name\":\"" + imageName + "\"}";
        String paramBase64 = null;
        try {
            paramBase64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(param.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String checkSum = DigestUtils.md5Hex(apikey + curTime + paramBase64);
        Map<String, String> header = new HashMap<String, String>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset = utf - 8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", appid);
        return header;
    }
}

